﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using EHTWebsite.Code;

/// <summary>
/// Author: toanvt
/// CreatedDate: 12/12/2011
/// Description: Danh sách Danh Mục Sản Phẩm
/// </summary>
public partial class Administrator_AdminProductCategorys : System.Web.UI.Page
{
    private Int32 danhMucID = -1;
    private DataTable dtDanhMucSanPham = new DataTable();
    private Int32 pageIndex = 1;
    private Int32 pageSize = 10;
    private Int32 totalRecord;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
        }
        catch (Exception)
        {
            pageIndex = 1;
        }

        try
        {
            danhMucID = Int32.Parse(Request.QueryString["DanhMucID"].ToString());
        }
        catch (Exception)
        {
            danhMucID = -1;
        }

        if (!Page.IsPostBack)
        {
            Int32 totalRecord = 0;
            dtDanhMucSanPham = DanhMucSanPhamProvider.GetDanhMucSanPhamsForBackEnd(-1, 1, 100000, out totalRecord).Tables[0];
            LoadDanhMucSanPhams(danhMucID);
            CreateTreeViewCategory();
        }
    }

    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: Lấy danh sách Danh Mục Sản Phẩm
    /// </summary>
    private void CreateTreeViewCategory()
    {
        TreeNode level0 = new TreeNode("Danh mục sản phẩm","-1");
        CreateTreeViewCategorys(level0,-1);
        tvCategorys.Nodes.Add(level0);
        ExpandPathOfTreeNode(tvCategorys.SelectedNode);
    }

    /// <summary>
    /// Author:tungvu90
    /// CreateDate:06/02/2012
    /// Description:Phương thức đệ quy taok TreeView
    /// </summary>
    /// <param name="treeNode"></param>
    /// <param name="chuyenMucChaID">mã chuyên mục cha</param>
    private void CreateTreeViewCategorys(TreeNode treeNode, Int32 chuyenMucChaID)
    {
        DataRow[] dataRowsSubCategorys = dtDanhMucSanPham.Select("ChuyenMucChaID=" + chuyenMucChaID.ToString());
        Int32 amountOfSubCategory = dataRowsSubCategorys.Count();

        //Điểm dừng đệ quy
        if (amountOfSubCategory == 0)
            return;

        TreeNode tn;

        for (Int32 i = 0; i < amountOfSubCategory; ++i)
        {
            Int32 subCategoryID = Int32.Parse(dataRowsSubCategorys[i]["DanhMucID"].ToString());
            tn = new TreeNode(dataRowsSubCategorys[i]["TenDanhMucVN"].ToString(), subCategoryID.ToString());
            tn.CollapseAll();
            CreateTreeViewCategorys(tn, subCategoryID);
            treeNode.ChildNodes.Add(tn);

            if (subCategoryID == danhMucID)
            {
                tn.Select();
            }

            tn = null;
        }
    }

    /// <summary>
    /// Author : toanvt
    /// CreatedDate : 10/02/2012
    /// Description : Expand Path of TreeNode
    /// </summary>
    /// <param name="tn"></param>
    private void ExpandPathOfTreeNode(TreeNode tn)
    {
        TreeNode tmpTreeNode = tn;

        if (tn == null)
            return;

        do
        {
            tmpTreeNode.Expand();
            TreeNode tmp = tmpTreeNode;
            tmpTreeNode = null;
            tmpTreeNode = tmp.Parent;
        }
        while (tmpTreeNode != null);
    }

    /// <summary>
    /// Author : TUNGV
    /// CreatedDate : 09/02/2012
    /// Description : Lấy danh sách sản phẩm theo danh mục ID
    /// </summary>
    /// <param name="danhMucID">Mã danh mục</param>
    private void LoadDanhMucSanPhams(Int32 danhMucID)
    {
        if (danhMucID > -1)
        {
            DataSet dsDanhMucSanPham = DanhMucSanPhamProvider.GetDanhMucSanPhamsForBackEnd(danhMucID, pageIndex, pageSize, out totalRecord);
            //if(dsDanhMucSanPham.Tables[0].Rows)
            rpDanhMucSanPham.DataSource = dsDanhMucSanPham;
            rpDanhMucSanPham.DataBind();

            foreach (RepeaterItem item in rpDanhMucSanPham.Items)
            {
                CheckBox ckPublish = (CheckBox)item.FindControl("ckPublish");

                if (ckPublish.Checked == true)
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/btncheck.png";
                }
                else
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/unpublish.jpg";
                }
            }
        }
        else
        {
            DataSet dsDanhMucSanPham = DanhMucSanPhamProvider.GetDanhMucSanPhamsForBackEnd(-1, 1, 100000, out totalRecord);
            rpDanhMucSanPham.DataSource = dsDanhMucSanPham;
            rpDanhMucSanPham.DataBind();
            foreach (RepeaterItem item in rpDanhMucSanPham.Items)
            {
                CheckBox ckPublish = (CheckBox)item.FindControl("ckPublish");

                if (ckPublish.Checked == true)
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/btncheck.png";
                }
                else
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/unpublish.jpg";
                }
            }
        }

        PaggingControl1.PageURL = "AdminProductCategorys.aspx?DanhMucID=" + danhMucID.ToString();
        PaggingControl1.PageIndex = pageIndex;
        PaggingControl1.TotalRecord = totalRecord;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminProductCategoryIU.aspx?danhMucID="+danhMucID);
    }

    protected void rpDanhMucSanPham_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        String cmdName = e.CommandName;
        Int32 DanhMucID = -1;

        try
        {
            DanhMucID = Int32.Parse(e.CommandArgument.ToString());
        }
        catch (Exception ex)
        { }

        if (cmdName == "delete1")
        {
            DataSet theDanhmucsanpham = DanhMucSanPhamProvider.GetDanhMucDanhMucSanPhamsByNhomDanhMucID(DanhMucID);
            DataSet theSanPham = DanhMucSanPhamProvider.GetSanPhambyDanhMucSanphamID(DanhMucID);

            if (theDanhmucsanpham.Tables[0].Rows.Count > 1)
            {
                this.lbMessage.CssClass = "";
                this.lbMessage.Text = "Bạn không thể xóa danh mục này vì có chứa danh mục con";
                return;
            }
            else if (theSanPham.Tables[0].Rows.Count > 0)
            {
                this.lbMessage.CssClass = "";
                this.lbMessage.Text = "Bạn không thể xóa danh mục này vì có chứa sản phẩm";
            }
            else
            {
                DanhMucSanPhamProvider.DeleteDanhMucSanPhamByDanhMucID(DanhMucID);
                LoadDanhMucSanPhams(danhMucID);
               // CreateTreeViewCategory();
                Response.Redirect("AdminProductCategorys.aspx");
            }
        }
        else if (cmdName == "change_number_of_order")
        {
            try
            {
                Int32 numberOfOrder = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                DanhMucSanPhamProvider.UpdateNumberOfOrderByDanhMucSanPhamId(DanhMucID,numberOfOrder);
            }
            catch (Exception ex)
            { }

            LoadDanhMucSanPhams(danhMucID);
        }
        else if (cmdName == "publish")
        {
            DanhMucSanPhamProvider.ChangePublishByDanhMucSanPhamID(DanhMucID);
            LoadDanhMucSanPhams(danhMucID);
        }
        else if (cmdName == "save_all")
        {
            foreach (RepeaterItem item in rpDanhMucSanPham.Items)
            {

                Int32 numberOfOrder = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                DanhMucID = Int32.Parse(((Literal)item.FindControl("ltrDanhMucSanPhamID")).Text.Trim());
                DanhMucSanPhamProvider.UpdateNumberOfOrderByDanhMucSanPhamId(DanhMucID,numberOfOrder);
            }

            LoadDanhMucSanPhams(danhMucID);
        }
    }

    protected void tvCategorys_SelectedNodeChanged(object sender, EventArgs e)
    {
        Response.Redirect("AdminProductCategorys.aspx?danhMucID=" + tvCategorys.SelectedNode.Value);
    }
}
